<template>
	<view class="jp-flex-column">
		<view class="jp-flex-row">
			<image class="image jp-expanded" :src="image" mode="scaleToFill" @click="$u.throttle(getCaptcha, 500)"></image>
		</view>
		
		<view style="text-align: end;">
			<text class="text-label">点击图片刷新</text>
		</view>
		<u-code-input v-model="parameter.code" fontSize="92rpx" space="32rpx" size="116rpx" :maxlength="4" mode="line"
			:hairline="true" @finish="finish">
		</u-code-input>
		<text class="text-label" style="margin-top: 16rpx;">请输入4个字符</text>
	</view>
</template>

<script>
	import props from "./props/props.js"

	export default {
		name: "verify-number",
		mixins: [props],
		data() {
			return {
				verifyCount: 0, //连续验证errorCountReset次后刷新图片
				image: '',
				parameter: {
					type: 'verify-number',
					code: '',
					uuid: ''
				}
			}
		},
		methods: {
			init() {
				this.parameter.uuid = ''
				this.$nextTick(() => {
					this.parameter.code = ''
				})
				this.getCaptcha()

			},
			async getCaptcha() {
				if (this.getGraphicCaptcha && typeof(this.getGraphicCaptcha) === 'function') {
					var res = await this.getGraphicCaptcha.call(uni.$u.$parent.call(this))
					// {
					// 	"code":200,
					// 	"data":{
					// 		"img":"",
					// 		"uuid":""
					// 	}
					// }
					if (res.code == 0 || res.code == 200) {
						this.verifyCount = 0
						if (res.data) {
							if (res.data.img.startsWith('data:image')) {
								this.image = res.data.img
							} else {
								this.image = 'data:image/png;base64,' + res.data.img
							}
						}
						this.parameter.uuid = res.data.uuid
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '父组件请实现 getGraphicCaptcha 方法，以获取图形验证码信息'
					})
				}
			},
			async finish(e) {
				if (this.validator && typeof(this.validator) === 'function') {
					var flag = await this.validator.call(uni.$u.$parent.call(this), this.parameter)
					if (flag == true) {
						this.$emit('finish', this.parameter)
					} else {
						if (++this.verifyCount >= this.errorCountReset) {
							this.init()
						} else {
							this.$nextTick(() => {
								this.parameter.code = ''
							})
						}
						uni.showToast({
							icon: 'none',
							title: '图形校验码错误'
						})
					}
				} else {
					console.warn('【jp-graphic-verification】validator 属性未定义,无法时时完成校验')
					this.$emit('finish', this.parameter)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.image {
		margin: 30rpx 0 16rpx 0;
		max-width: 100%;
		height: 160rpx;
		max-height: 100%;
		background-color: #00000020;
		border-radius: 4rpx;
	}
</style>